﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using Chat;

namespace Chat.GUI
{
    public partial class IPEndPointDialog : Chat.GUI.BaseDialog
    {
        public IPEndPointDialog()
        {
            InitializeComponent();
        }

        private IPEndPoint ipEndPoint; // model

        public IPEndPoint IpEndPoint
        {
            get { return ipEndPoint; }
            protected set { ipEndPoint = value; }
        }

        protected override bool ValidateData()
        {
            bool isError = false;

            IPAddress ip = null;

            try
            {
                ip = IPAddress.Parse(this.txtIPAddress.Text);
                ClearError(this.txtIPAddress);
            }
            catch (Exception)
            {
                isError = true;
                ShowErrorMsg(this.txtIPAddress, "Invalid IP Address");
            }

            Nullable<PortNumber> port = null;

            try
            {
                port = new PortNumber((int)this.numPort.Value);
                ClearError(this.numPort);
            }
            catch (Exception)
            {
                isError = true;
                ShowErrorMsg(this.numPort, "Invalid Port");
            }
            
            return !isError;
        }

        protected override void UpdateModel()
        {
            IPAddress ip = IPAddress.Parse(this.txtIPAddress.Text);

            if (IpEndPoint == null)
            {
                IpEndPoint = new IPEndPoint(ip, (int)this.numPort.Value);
            }
            else
            {
                IpEndPoint.Address = ip;
                IpEndPoint.Port = (int)this.numPort.Value;
            }
        }

        protected override bool RestoreFromModel()
        {
            if (IpEndPoint == null)
                return false;

            this.txtIPAddress.Text = IpEndPoint.Address.ToString();
            this.numPort.Value = IpEndPoint.Port;

            return true;
        }
    }
}
